<template>
  <div class="container">
    <el-card class="app-container">
      <div slot="header" class="clearfix">
        <span>技师管理</span>
      </div>
      <!-- 搜索区域 -->
      <el-form ref="searchForm" label-width="120px" :model="search" class="filter-form">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="搜索:">
              <el-input v-model="search.search" size="small" placeholder="技师姓名或手机号" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="入驻状态:">
              <el-select v-model="search.onboarding_status" size="small" placeholder="请选择入驻状态">
                <el-option label="待审核" value="10" />
                <el-option label="待支付" value="20" />
                <el-option label="已入驻" value="30" />
                <el-option label="已拒绝" value="40" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" style="display: flex; justify-content: flex-start;">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
              <el-button size="medium" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div style="width: 100%;">
        <el-table
          v-loading="tableloading"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="real_name" label="技师姓名" align="center" />
          <el-table-column prop="age" label="年龄" align="center" />
          <el-table-column prop="phone" label="联系电话" align="center" />
          <el-table-column prop="id_card" label="身份证号" align="center" />
          <el-table-column prop="full_address" label="地址" align="center" />
          <el-table-column prop="status" label="入驻状态" align="center">
            <template slot-scope="scope">
              {{ getStatusText(scope.row.onboarding_status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button v-if="!scope.row.loading" type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
              <i v-else class="el-icon-loading" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      title="技师详情"
      :visible.sync="detailDialog.visible"
      width="70%"
      @close="closeDetailDialog"
    >
      <div v-if="detailDialog.data" class="detail-info">
        <el-form label-width="140px" size="small">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="技师ID:">
                <span>{{ detailDialog.data.id }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技师姓名:">
                <span>{{ detailDialog.data.real_name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话:">
                <span>{{ detailDialog.data.phone }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄:">
                <span>{{ detailDialog.data.age }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身高:">
                <span>{{ detailDialog.data.height }}cm</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="体重:">
                <span>{{ detailDialog.data.weight }}kg</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号:">
                <span>{{ detailDialog.data.id_card || '-' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址:">
                <span>{{ detailDialog.data.full_address || '-' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入驻状态:">
                <span>{{ getStatusText(detailDialog.data.onboarding_status) }}</span>
              </el-form-item>
            </el-col>
            <!-- 审核拒绝信息 -->
            <template v-if="detailDialog.data.onboarding_status === 40">
              <el-col :span="12">
                <el-form-item label="审核拒绝原因:">
                  <span>{{ detailDialog.data.rejection_reason }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="审核拒绝时间:">
                  <span>{{ formatDate(detailDialog.data.rejected_at) }}</span>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="12">
              <el-form-item label="服务类型:">
                <span>{{ detailDialog.data.service_content }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作经验描述:">
                <span>{{ detailDialog.data.work_experience }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间:">
                <span>{{ formatDate(detailDialog.data.created_at) }}</span>
              </el-form-item>
            </el-col>

            <!-- 技师个人照片 -->
            <el-col :span="12">
              <el-form-item label="技师个人照片:">
                <div v-if="detailDialog.data.person_avatar && ((typeof detailDialog.data.person_avatar === 'string' && detailDialog.data.person_avatar.trim().length > 0) || (Array.isArray(detailDialog.data.person_avatar) && detailDialog.data.person_avatar.length > 0))" class="image-multi">
                  <el-image
                    v-for="(photo, index) in (typeof detailDialog.data.person_avatar === 'string' ? detailDialog.data.person_avatar.split(',') : detailDialog.data.person_avatar)"
                    :key="index"
                    :src="typeof photo === 'string' ? photo.trim() : photo"
                    :preview-src-list="typeof detailDialog.data.person_avatar === 'string' ? detailDialog.data.person_avatar.split(',').map(p => typeof p === 'string' ? p.trim() : p) : detailDialog.data.person_avatar"
                    fit="fill"
                    style="width: 200px; height: 150px; margin-right: 10px; margin-bottom: 10px;"
                  />
                </div>
                <span v-else>未上传</span>
              </el-form-item>
            </el-col>
            <!-- 身份证正面 -->
            <el-col :span="12">
              <el-form-item label="身份证正面:">
                <div v-if="detailDialog.data.id_card_front" class="image-single">
                  <el-image
                    :src="detailDialog.data.id_card_front"
                    :preview-src-list="[detailDialog.data.id_card_front]"
                    fit="fill"
                    style="width: 200px; height: 150px;"
                  />
                </div>
                <span v-else>未上传</span>
              </el-form-item>
            </el-col>
            <!-- 身份证反面 -->
            <el-col :span="12">
              <el-form-item label="身份证反面:">
                <div v-if="detailDialog.data.id_card_back" class="image-single">
                  <el-image
                    :src="detailDialog.data.id_card_back"
                    :preview-src-list="[detailDialog.data.id_card_back]"
                    fit="fill"
                    style="width: 200px; height: 150px;"
                  />
                </div>
                <span v-else>未上传</span>
              </el-form-item>
            </el-col>
            <!-- 资格证书照片 -->
            <el-col :span="12">
              <el-form-item label="资格证书照片:">
                <div v-if="detailDialog.data.certification && ((typeof detailDialog.data.certification === 'string' && detailDialog.data.certification.trim().length > 0) || (Array.isArray(detailDialog.data.certification) && detailDialog.data.certification.length > 0))" class="image-multi">
                  <el-image
                    v-for="(photo, index) in (typeof detailDialog.data.certification === 'string' ? detailDialog.data.certification.split(',') : detailDialog.data.certification)"
                    :key="index"
                    :src="typeof photo === 'string' ? photo.trim() : photo"
                    :preview-src-list="typeof detailDialog.data.certification === 'string' ? detailDialog.data.certification.split(',').map(p => typeof p === 'string' ? p.trim() : p) : detailDialog.data.certification"
                    fit="fill"
                    style="width: 200px; height: 150px; margin-right: 10px; margin-bottom: 10px;"
                  />
                </div>
                <span v-else>未上传</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <template v-if="detailDialog.data && detailDialog.data.onboarding_status === 10">
          <el-button :loading="btnloading1" type="primary" @click="handleApprove">审核通过</el-button>
          <el-button :loading="btnloading2" type="danger" @click="handleReject">审核不通过</el-button>
        </template>
        <el-button type="primary" @click="closeDetailDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTechnicianList, getTechnicianDetail, technicianApprovedOk, TechnicianApprovedNo } from '@/api/user'
export default {
  data() {
    return {
      search: {
        search: null,
        onboarding_status: null
      },
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      tableloading: false,
      btnloading1: false,
      btnloading2: false,
      // 详情弹窗
      detailDialog: {
        visible: false,
        data: null
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.search = {
        search: null,
        onboarding_status: null
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },
    formatDate(timestamp) {
      if (!timestamp) return '-' // 如果没有时间戳，返回 '-'或其他占位符

      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 打开详情弹窗
    async handleDetail(row) {
      try {
        // 设置当前行的loading状态为true
        const rowIndex = this.tableData.findIndex(item => item.id === row.id)
        if (rowIndex !== -1) {
          this.$set(this.tableData[rowIndex], 'loading', true)
        }

        const res = await getTechnicianDetail({ id: row.id })

        this.detailDialog.data = res.data
        this.detailDialog.visible = true
      } catch (error) {
        this.$message.error('获取详情失败')
        console.error('获取技师详情失败:', error)
      } finally {
        // 设置当前行的loading状态为false
        const rowIndex = this.tableData.findIndex(item => item.id === row.id)
        if (rowIndex !== -1) {
          this.$set(this.tableData[rowIndex], 'loading', false)
        }
      }
    },
    // 关闭详情弹窗
    closeDetailDialog() {
      this.detailDialog.visible = false
      this.detailDialog.data = null
    },
    // 审核通过
    async handleApprove() {
      try {
        this.btnloading1 = true

        await technicianApprovedOk({ id: this.detailDialog.data.id })

        this.$message.success('审核通过成功')
        this.closeDetailDialog()
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('审核失败')
          console.error('审核通过失败:', error)
        }
      } finally {
        this.btnloading1 = false
      }
    },
    // 审核不通过
    async handleReject() {
      try {
        // 弹出输入框获取审核不通过原因
        this.$prompt('请输入审核不通过的原因', '审核不通过', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (value) => {
            if (!value || value.trim().length === 0) {
              return '拒绝原因不能为空'
            }
            if (value.length > 200) {
              return '拒绝原因不能超过200个字符'
            }
            return true
          },
          inputPlaceholder: '请输入审核不通过的具体原因'
        }).then(async({ value }) => {
          try {
            this.btnloading2 = true
            // 调用实际的审核不通过API
            await TechnicianApprovedNo({
              id: this.detailDialog.data.id,
              reason: value
            })

            this.$message.success('已拒绝审核')
            this.closeDetailDialog()
            this.fetchData() // 重新加载数据
          } catch (error) {
            this.$message.error('审核失败')
            console.error('审核不通过失败:', error)
          } finally {
            this.btnloading2 = false
          }
        }).catch(() => {
          // 用户取消输入
          console.log('用户取消了审核拒绝操作')
        })
      } catch (error) {
        console.error('处理审核拒绝时出错:', error)
      }
    },
    // 获取入驻状态文本
    getStatusText(status) {
      switch (status) {
        case 10: return '待审核'
        case 20: return '待支付'
        case 30: return '已入驻'
        case 40: return '已拒绝'
        default: return '未知状态'
      }
    },
    async fetchData() {
      try {
        // 显示表格加载中状态
        this.tableloading = true
        const queryParams = {
          pageSize: this.pagination.pageSize,
          page: this.pagination.page,
          search: this.search.search,
          onboarding_status: this.search.onboarding_status
        }
        // 调用实际的技师列表API
        const res = await getTechnicianList(queryParams)
        // 检查返回数据结构是否正确
        if (res.data && res.data.list && Array.isArray(res.data.list)) {
          this.tableData = res.data.list

          this.pagination.total = res.data.total || 0
        } else {
          this.tableData = []
          this.pagination.total = 0
          console.warn('获取的技师列表数据格式不正确:', res)
        }
      } catch (error) {
        this.$message.error('获取技师列表失败')
        console.error('获取技师列表失败:', error)
        // 设置空数据以避免表格显示异常
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.tableloading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-radio__original {
  display: none !important;
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.filter-form {
  padding: 16px;
  padding-bottom: 0;
  margin-bottom: 6px;
  .el-select {
    width: 100%;
  }
}

.detail-info {
  font-size: 14px;
  /* 确保不出现滚动条 */
  max-height: none;
  overflow-y: visible;
}

.detail-info .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 图片展示样式 */
.image-single {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 5px;
}

.image-multi {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  margin-top: 5px;
}

/* 视频容器样式 */
.video-container {
  margin-top: 5px;
}

.tab-container {
  margin-left: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}
.filter-row > * {
  flex: 1;
  min-width: 200px;
  max-width: calc(50% - 10px);
}
.filter-actions {
  display: flex;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
.add {
  ::v-deep .el-dialog__body{
    max-height: 600px;
    overflow-y: auto;
  }
  ::v-deep .el-form-item {
    margin-bottom: 8px;
    .el-form-item__error {
      padding-top: 0px;
      transform: translateY(-2px)
    }
    .el-select {
      width: 100%;
    }
  }
}
.xg {
  ::v-deep .el-dialog__body{
    padding: 20px;
  }
}
.xxzf {
  ::v-deep .el-form-item {
    margin-bottom: 8px;
  }
  ::v-deep .el-form-item__error {
    padding-top: 0px;
    transform: translateY(-2px)
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px 15px;
  }
}
</style>
